import Controller from '../../decorators/controller'
import get from '../../decorators/get'
import post from '../../decorators/post'
import BaseController from '../base'
import ProductDao from '../../dao/productDao'
import ProductOptionDao from '../../dao/productOptionDao'
import SkuDao from '../../dao/skuDao'
import db from '../../util/db'

var uuid = require('node-uuid')
@Controller('/api/admin/products')
export default class extends BaseController {
    @get("/")
    list() {
        var params = this.getParams()
        // this.ctx.body = "hello world"
        return ProductDao.where(params).page({
            from: params.from,
            limit: params.size
        }).select()
    }

    @get("/count")
    count() {
        var params = this.getParams()
        // this.ctx.body = "hello world"
        return ProductDao.where(params).count()
    }

    @post("/")
    async add() {
        var result = null;
        result = await db.transaction(async (t) => {
            var payload = this.getBody()
            var {clientId} = await this.getCurrentUser()

            payload.clientId = clientId
            if (payload.optionValues) {
                payload.optionValues = payload.optionValues.map(item => item.id)
            }

            //启动事务
            //create sku =>id
            var createSkus = []
            for (let i = 0; i < payload.skus.length; i++) {
                var sku = payload.skus[i]
                delete sku.id
                var _sku = await SkuDao.add(sku, t)
                createSkus.push(_sku)
            }
            payload.skus = createSkus.map(item => item.id)
            var newProduct = await ProductDao.add(payload, t)
            // update skus.productId
            for (let i = 0; i < createSkus.length; i++) {
                await SkuDao.update(createSkus[i].id, {productId: newProduct.id}, t)
            }
            result = newProduct
            return result
        }).catch(e => {
            console.error("e 生成 product失败====>", e)
            this.ctx.throw(501, e)
        })
        return result
    }

    @get("/detail")
    async one() {
        var {id} = this.getParams()
//         var results= await ProductDao.selectBySql(
//             `select p.*, u."name" as username from "product" p
// left join "user" u on u."id"=p."userId"
// where p."id"=${id}`
//         )
        var results = await ProductDao.where({id: 1})
            .leftJoin("user",
                '"user"."id"="product"."userId"',
                '"user".name as userName').select()
        return results[0]
    }

    @post("/generateSkus")
    async generateSkus() {
        /*
        options:
            [
              {id: 4664401618357248, values: ["xl"]} ,id productType=>name
              {id: 4664400888253441, values: ["5ml"]}
        */
        //  to
        /*
        * sku
        *   options []
        *        value1
        *        value2
        * */
        var {options} = this.getBody()
        var _adapterOptionss = []
        for (let i = 0; i < options.length; i++) {
            var option = options[i]
            var {name} = await ProductOptionDao.findById(option.id)
            var __adapterOptions = []
            option.values.map((value, index) => {
                __adapterOptions.push({
                    id: new Date().getTime() + index,
                    name: name,
                    value
                })
            })
            _adapterOptionss = _adapterOptionss.concat([__adapterOptions])

        }
        // options = [
        //     [{id: 1, value: "xl"}, {id: 1, value: "m"}, {id: 1, value: "l"}],
        //     [{id: 2, value: "20ml"}, {id: 2, value: "50ml"},],
        //     [{id: 3, value: "red"}, {id: 3, value: "yellow"},],
        // ]
        var resultOptions = []
        resultOptions = this.loopNext(_adapterOptionss)
        resultOptions = resultOptions.filter(item => item.length === _adapterOptionss[0].length)
        //特殊情况 如果只有一条 拆开来
        if (resultOptions.length === 1) {
            return resultOptions[0].map(option => {
                return {
                    options: [option], id: uuid.v1()
                }
            })
        }
        return resultOptions.map(options => {
            return {
                options, id: uuid.v1()
            }
        })
    }

    loopNext(options, resultOptions = []) {
        var option = options[0];
        var nextOption = options[1]
        var nextNextOption = options[2]
        var isOver = nextNextOption ? false : true
        if (!option) {
            return resultOptions
        }
        if (!nextOption) {
            return options
        }
        option.map(value1 => {
            nextOption.map(value2 => {
                resultOptions = resultOptions.concat(
                    [[...this.fixedExpandArray(value1), ...this.fixedExpandArray(value2)]]
                )
            })
        })
        options = options.splice(2, options.length)
        if (isOver) {
            return resultOptions
        }

        return this.loopNext(
            [resultOptions, ...this.fixedExpandArray(options)],
            resultOptions
        )

    }

    fixedExpandArray(_array) {
        if (_array.constructor === Array) {
            return _array
        } else {
            return [_array]
        }
    }

}


